package com.whfc.quality.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.whfc.common.exception.BizException;
import com.whfc.common.result.ListData;
import com.whfc.common.result.PageData;
import com.whfc.common.util.DateUtil;
import com.whfc.common.util.MathUtil;
import com.whfc.common.util.PageUtil;
import com.whfc.quality.dao.*;
import com.whfc.quality.dto.*;
import com.whfc.quality.entity.QualityCheckStatisticsDay;
import com.whfc.quality.entity.QualityIssueType;
import com.whfc.quality.enums.QualityCheckState;
import com.whfc.quality.enums.QualityOptionType;
import com.whfc.quality.service.MdQualityBoardService;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 大屏-质量 service
 *
 * @author qzexing
 * @version 1.0
 * @date 2021/11/17 17:07
 */
@DubboService(interfaceClass = MdQualityBoardService.class, version = "1.0.0")
public class MdQualityBoardServiceImpl implements MdQualityBoardService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private QualityCheckMapper qualityCheckMapper;

    @Autowired
    private QualityCheckLogMapper qualityCheckLogMapper;

    @Autowired
    private QualityCheckImgMapper qualityCheckImgMapper;

    @Autowired
    private QualityIssueTypeMapper issueTypeMapper;


    @Autowired
    private QualityCheckStatisticsDayMapper qualityCheckStatisticsDayMapper;

    @Override
    public ListData<MdQualityStatisticsDTO> getCheckTypeStatistics(Integer deptId, Date startTime, Date endTime) throws BizException {
        logger.info("大屏-质量-问题类型统计, deptId:{}, startTime:{}, endTime:{}", deptId, startTime, endTime);
        if (startTime != null) {
            startTime = DateUtil.getDateBegin(startTime);
        }
        if (endTime != null) {
            endTime = DateUtil.getDateEnd(endTime);
        }
        List<QualityIssueNumDTO> list = qualityCheckMapper.selectIssueTypeNum(deptId, startTime, endTime);
        if (list.isEmpty()) {
            return new ListData<>(Collections.emptyList());
        }
        List<MdQualityStatisticsDTO> statisticsList = new ArrayList<>();
        for (QualityIssueNumDTO qualityIssueNumDTO : list) {
            MdQualityStatisticsDTO statisticsDTO = new MdQualityStatisticsDTO();
            Long issueTypeId = qualityIssueNumDTO.getIssueTypeId();
            QualityIssueType qualityIssueType = issueTypeMapper.selectByIssueTypeId(issueTypeId);
            if(null == qualityIssueType){
                statisticsDTO.setIssueTypeName("其他");
            }else{
                statisticsDTO.setIssueTypeName(qualityIssueType.getName());
            }
            statisticsDTO.setNum(qualityIssueNumDTO.getNum());
            statisticsList.add(statisticsDTO);
        }
        statisticsList.sort(Comparator.comparing(MdQualityStatisticsDTO::getNum).reversed());
        return new ListData<>(statisticsList);
    }

    @Override
    public PageData<MdQualityCheckDTO> getCheckList(Integer deptId, Integer pageNum, Integer pageSize) throws BizException {
        logger.info("大屏-质量-检查记录列表, deptId:{}, pageNum:{}, pageSize:{}", deptId, pageNum, pageSize);
        PageHelper.startPage(pageNum, pageSize);
        List<MdQualityCheckDTO> list = qualityCheckMapper.selectMdBoardCheckList(deptId);
        return PageUtil.pageData(PageInfo.of(list));
    }

    @Override
    public MdQualityCheckAnalysisDTO getCheckAnalysis(Integer deptId) throws BizException {
        logger.info("大屏-质量-问题分析, deptId:{}", deptId);
        MdQualityCheckAnalysisDTO analysisDTO = new MdQualityCheckAnalysisDTO();
        Date today = new Date();
        // 获取今日新增
        Integer newIssueNum = qualityCheckMapper.countCheckNewIssue(deptId, DateUtil.getDateBegin(today), DateUtil.getDateEnd(today));
        analysisDTO.setNewIssueNum(newIssueNum);
        // 今日待整改
        Integer todoIssueNum = qualityCheckMapper.countCheckToBeRectified(deptId);
        analysisDTO.setTodoIssueNum(todoIssueNum);
        //今日已完成
        Integer completeIssueNum = qualityCheckMapper.countCheckComplete(deptId, today);
        // 累计整改完成率
        //总检查数量
        Integer totalCheckNum = qualityCheckMapper.countCheckNum(deptId, null);
        //已完成数
        Integer completeCheckNum = qualityCheckMapper.countCheckNum(deptId, QualityCheckState.SUCCESS.getValue());
        analysisDTO.setRectificationRate(MathUtil.round((completeCheckNum / (totalCheckNum * 1.0)), 2));
        // 近七天质量检查情况
        List<MdQualityCheckAnalysisDTO> list = new ArrayList<>();
        //近七天时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(today);
        calendar.add(Calendar.DAY_OF_MONTH, -7);
        Date startTime = calendar.getTime();
        List<Date> dayList = DateUtil.getDayList(startTime, today);
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
        for (int i = 0; i < dayList.size(); i++) {

            Date date = dayList.get(i);
            MdQualityCheckAnalysisDTO checkAnalysisDTO = new MdQualityCheckAnalysisDTO();
            checkAnalysisDTO.setDate(date);

            int nIssueNum = 0;
            int tdIssueNum = 0;
            int cIssueNum = 0;
            String dateStr = sdf.format(date);
            if (i == dayList.size() - 1) {
                nIssueNum = newIssueNum;
                tdIssueNum = todoIssueNum;
                cIssueNum = completeIssueNum;
                dateStr = "今天";
            } else {
                QualityCheckStatisticsDay statisticsDay = qualityCheckStatisticsDayMapper.selectByDeptIdAndDate(deptId, date);
                if (statisticsDay != null) {
                    nIssueNum = statisticsDay.getNewIssueNum();
                    tdIssueNum = statisticsDay.getTodoIssueNum();
                    cIssueNum = statisticsDay.getCompleteIssueNum();
                }
                //处理时间字符串
                if (i == dayList.size() - 2) {
                    dateStr = "昨天";
                }
            }
            checkAnalysisDTO.setNewIssueNum(nIssueNum);
            checkAnalysisDTO.setTodoIssueNum(tdIssueNum);
            checkAnalysisDTO.setCompleteIssueNum(cIssueNum);
            checkAnalysisDTO.setDateStr(dateStr);
            list.add(checkAnalysisDTO);
        }
        analysisDTO.setList(list);
        return analysisDTO;
    }

    @Override
    public PageData<MdQualityCheckLogDTO> getCheckLog(Integer deptId, Integer pageNum, Integer pageSize) throws BizException {
        logger.info("大屏-质量-问题动态, deptId:{}, pageNum:{}, pageSize:{}", deptId, pageNum, pageSize);
        PageHelper.startPage(pageNum, pageSize);
        List<MdQualityCheckLogDTO> list = qualityCheckLogMapper.selectLogByDeptId(deptId);
        PageHelper.clearPage();
        if (!list.isEmpty()) {
            for (MdQualityCheckLogDTO mdQualityCheckLogDTO : list) {
                if (QualityOptionType.REPORT.getValue().equals(mdQualityCheckLogDTO.getOpType())) {
                    mdQualityCheckLogDTO.setOpDesc(mdQualityCheckLogDTO.getCheckDesc());
                }
                //获取图片
                List<String> imgUrlList = qualityCheckImgMapper.selectByCheckId(mdQualityCheckLogDTO.getCheckId(),
                        mdQualityCheckLogDTO.getOpType(), mdQualityCheckLogDTO.getLogId());
                if (imgUrlList.isEmpty()) {
                    //获取检查图片
                    imgUrlList = qualityCheckImgMapper.selectByCheckId(mdQualityCheckLogDTO.getCheckId(),
                            QualityOptionType.REPORT.getValue(), null);
                }
                if (!imgUrlList.isEmpty()) {
                    mdQualityCheckLogDTO.setImgUrl(imgUrlList.get(0));
                }
            }
        }
        return PageUtil.pageData(PageInfo.of(list));
    }
}
